<template>
  <div>
    <!-- el-tree组件 渲染树形权限数据 -->
    <el-tree
      ref="tree"
      node-key="id"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      :data="treeList"
      :props="{label:'name'}"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hAssignPer">确定</el-button>
      <el-button @click="hCancel">取消</el-button>
    </div>
  </div>
</template>

<script>

import { getPermissionList } from '@/api/permissions'
import { tranDataToTree } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/settings'

export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      treeList: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 给角色分配权限
    async hAssignPer() {
      try {
        // 获取选中的权限
        const permIds = this.$refs.tree.getCheckedKeys()
        console.log('this.$refs.tree.getCheckedKeys', permIds)
        await assignPerm({ id: this.id, permIds: permIds })
        this.$emit('close')
        // 保存数据
      } catch (err) {
        console.log('assignPerm', err)
      }
    },
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log(res, 'loadPermissionList')
        // 保存数据
        this.treeList = tranDataToTree(res.data)
        // 获取当前角色的权限
        const info = await getRoleDetail(this.id)
        console.log(info, 'info')
        // 让当前的角色拥有的权限处于选中状态
        this.$refs.tree.setCheckedKeys(info.data.permIds)
      } catch (error) {
        console.log(error)
      }
    },
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
